﻿using System.Threading;
using LucyGrid;
using System;
using System.Linq;

namespace LucyGridNode
{
	class Program
	{
		static void Main(string[] args)
		{
			if(args.Length > 1 && args[0] == "WORKER")
				GridUtils.Mode = GridUtils.ActorType.WORKER;
			else
				GridUtils.Mode = GridUtils.ActorType.GRIDNODE;
			int res = 0;
			try
			{
				if ("*".Equals(args.Skip(1).FirstOrDefault()))
					args = AttachToAny(args);
				new GridNode(GridUtils.Mode, args.Length > 1 ? args[1] : null);
				GridUtils.NotifyLog("NODE,INFO", "GridNode end");
			}
			catch (Exception ex)
			{
				GridUtils.NotifyLog("NODE,INFO", "Error executing gridnode: {0}", ex);
				Console.Error.WriteLine(ex.ToString());
				res = -1;
			}
			finally
			{
				GridUtils.Finalize();
			}
			Environment.Exit(res);
		}
		/// <summary>
		/// Listen for the first grid notfication and attach to it
		/// </summary>
		/// <param name="args"></param>
		/// <returns></returns>
		private static string[] AttachToAny(string[] args)
		{
			var wait = new ManualResetEvent(false);
			var c = new GridComm().StartListener(null, (ev, o) =>
			{
				if (ev == GridCommEvents.grid)
				{
					args[1] = o["Endpoint"].ToString();
					wait.Set();
				}
			});
			wait.WaitOne(20000);
			return args;
		}
	}
}
